package com.loongtech.bi.manager.realTime;

import com.loongtech.bi.entity.realTime.EntityAuanyCreateuser;
import com.loongtech.core.jpa.manager.ManagerQueryCacheBase;
import com.loongtech.core.util.Time;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Author: mawenbin
 * Description:  实时数据-分服最新在线数据
 * Date: 14:32 2018/03/12
 */
@Service
public class ServerOnlineNumManager extends ManagerQueryCacheBase<EntityAuanyCreateuser> {
	private static final long serialVersionUID = 1L;
	
	private static JSONObject getJSONObj(Object serverId,Object onum,Object name) {
		try {
			JSONObject jObject =new JSONObject();
			jObject.put("serverCode", serverId);
			jObject.put("onlineCnt", onum);
			jObject.put("serverName", name);
			return jObject;
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 返回json字符串
	 * 
	 * @param hour
	 * @return
	 */
	public String getServerOnlineNum(int hour) {
		List<Object[]> list = getServerOnlineData(hour);
		
		//判断参数
		JSONArray jArray = new JSONArray();
		if (null == list || list.isEmpty()) {
			return jArray.toString();
		}

		//保存已经处理的服务器id
		Set<Object> set = new HashSet<>();
		for (Object[] line : list) {
			Object serverId = line[0];
			if (null == serverId || set.contains(serverId)) {
				continue;
			}

			set.add(serverId);
			JSONObject jObject = getJSONObj(serverId, line[2], line[3]);
			if (null != jObject) {
				jArray.put(jObject);
			}
		}

		return jArray.toString();
	}

	/**
	 * 带一个参数表明时间差
	 * @param hour
	 * @return
	 */
	private List<Object[]> getServerOnlineData(int hour) {
		//因为时区偏移毫秒数
		long curTime = System.currentTimeMillis() - hour * 60 * 60 * 1000L;
		//从最近30分钟在线数据中获取
		long offset  = curTime - 30 * 60 * 1000L;
		long dayTime = Time.getBeginningOfDay(curTime)/1000L - 150;
		String logTime = Time.formatTime(offset, "yyyy-MM-dd HH:mm:ss");
		String ilogDay = Time.formatTime(offset, "yyyyMMdd");
		
		String sql = "select b.serverid,b.quantum,b.num,c.name from (select serverid,quantum,sum(num) as num from "
				+"(select serverid,channelid,max(num) as num,floor((unix_timestamp(logtime) - " + dayTime + ")/300) as quantum "
				+" from realtime_onlinenum where logday>="+ilogDay+" and logtime>='"+logTime+"' group by serverid,channelid,quantum having quantum <288) as a "
				+"group by serverid,quantum) as b left join bi_server as c on b.serverid=c.id order by b.serverid,b.quantum desc";
        return queryBySql(sql);
	}
}